"use strict"

function addModalSetting()
{
    var ModalSetting = '\
        <div class="modal fade " id="ModalSetting" style="--bs-modal-width: 600px;">\
          <div class="modal-dialog modal-dialog-centered" role="document">\
            <div class="modal-content" style="background: #23293D; margin: auto;">\
              <div class="modal-header px-0">\
                <a class="modal-title btn" style="font-size: larger;" onclick="$(\'#ModalSetting\').modal(\'hide\')" > <img src="my_imgae/arrow-left.png" width="22" alt=""> Setting </a>\
              </div>\
              <div class="modal-body">\
              </div>\
              <div class="modal-footer">\
                <div class="btn blogcradbtn mx-1" id="Set_Delete" onclick="onSettingDelete(this)"\
                  style="padding-block: 10px; "> Delete\
                </div>\
                <div class="btn blogcradbtn mx-1" id="Set_Submit" onclick="onSettingSubmit(this)"\
                  style="padding-block: 10px; "> Submit\
                </div>\
              </div>\
            </div>\
          </div>\
        </div>\
        ';

    if($("#ModalSetting").length == 0) {
      jQuery('body').append(ModalSetting);
    }
}


function TableInsert()
{
    var innerHTML0 = '\
                    <tbody>\
                        <tr id="myid" onclick="liOnclick(this)">\
                    ';
                    
    var innerHTML1 = '\
                    <td>arguments</td>';

    var innerHTML2= '\
                        </tr>\
                    </tbody>\
                    ';
                    
    var innerHTML = innerHTML0.replace(/myid/g, arguments[1]);

    for (var key in arguments[3]) {
        var value = arguments[3][key];
        if(value=="null"||value==null){
          value = "";
        }
        innerHTML += innerHTML1.replace(/arguments/g, value);
    }
    
    innerHTML += innerHTML2;

    var item_new = document.createElement("tbody");
    item_new.innerHTML = innerHTML;
    document.getElementById(arguments[0]).appendChild(item_new);

}

let dataRecord = null;
let dataOffset = 0;
let dataCount  = 20;
let dataCountMax = 0;
let dataWHERE = null;


function paginate_button()
{
    var all = dataCountMax;
    var maxpage = Math.floor(all/dataCount);
    var minpage = Math.floor(dataOffset/dataCount);
    minpage = minpage-3;
    if(minpage>(maxpage-7)) minpage = maxpage-7+1;
    if(minpage<0) minpage = 0;

    var pagenum = $(".dataTables_paginate .pagenum")
    for(var ii=0;ii<7;ii++){
      $(pagenum[ii]).html((minpage+ii)+1);
      $(pagenum[ii]).attr("data",(minpage+ii)*dataCount);
      if(minpage+ii>maxpage){
        $(pagenum[ii]).addClass("d-none");
      }
      else{
        $(pagenum[ii]).removeClass("d-none");
      }
      if((minpage+ii)*dataCount==dataOffset){
        $(pagenum[ii]).addClass("current");
        $(".dataTables_paginate .previous" ).attr("data",dataOffset-dataCount*7>0?dataOffset-dataCount*7:0)
        $(".dataTables_paginate .next").attr("data",dataOffset+dataCount*7<all?dataOffset+dataCount*7: maxpage*dataCount )
      }
      else{
        $(pagenum[ii]).removeClass("current");
      }
    }

}

function onPageitem(e){
    e = e.currentTarget ?? e
    var index = Number.parseInt($(e).attr("data"));
    if(index!=dataOffset){
      dataOffset = index;
      Table_Show();
    }
}

function on_Search(){
    var dropdown_filter = $(".dropdown-filter")

    var WHERE = "";
    for (var ii=0 ; ii < dropdown_filter.length; ii++ ) {
        var key = $(dropdown_filter[ii]).find(".dropdown-text").html()
        var operator = $(dropdown_filter[ii]).find(".dropdown-operator")[0].innerText
        var input = $(dropdown_filter[ii]).find("input").val()
        if(input!=""){
            if(WHERE==""){
              WHERE = "WHERE "
            }
            else{
              WHERE += " AND "
            }

            WHERE += "`" + key + "` " + operator + " '" + input + "'"
        }
    }

    console.log("on_Search", WHERE );

    dataOffset = 0;
    dataWHERE = WHERE;
    Table_Show()

}

function bodyNavClick(e){
    console.log("bodyNavClick", e.innerText );

    var dropdown_text = $(e).parents(".dropdown").find(".dropdown-text")[0];
    $(dropdown_text).html( e.innerText );

}


function ShowModalSetting(index){
  $('#ModalSetting').modal('show')

  var modal_body = $("#ModalSetting .modal-body");
  if(modal_body!=undefined){
    // 删除之前的数据
    var mytableEle = modal_body[0];
    for (var i = mytableEle.children.length - 1; i >= 0; i--) {
        mytableEle.children[i].remove();
    }

    var innerHTML = '\
                      <div class="row mb-2 justify-content-center align-items-center" >\
                        <div class="col-sm-4 col-5"><h5 class="f-w-500 mb-0">\
                          {key}\
                        <span class="pull-end">:</span></h5></div>\
                        <div class="col-sm-8 col-7">\
                          <input data="{key}" value="{value}" type="text" class="form-control" vaule="vaule" style="font-size: larger; border: none;padding-left: 10px; height: 36px;" >\
                        </div>\
                      </div>\
                      ';

    var table111 = $("#recordtable #thead_table111 .sorting");

    var item = dataRecord[ (index != "-1" ? index : "0") ];

    for (var key in item) {
        var html = innerHTML.replace(/{key}/g, getModalKey(key)  );
        html = html.replace(/{value}/g, (index != "-1" ? item[key] : "") );

        var item_new = document.createElement("div");
        item_new.innerHTML = html;
        $(item_new).appendTo( $(modal_body) );

    }

    $('#ModalSetting').attr("data",  (index != "-1" ? index : "") )
  }

}

function getModalKey(key){
    return key
}

function new_filter(){
    var dropdown_filter = $(".dropdown-filter")[0];
    $(dropdown_filter).clone().appendTo($(dropdown_filter).parent());

}

function GetItemValue(key){
  var input = $('#ModalSetting input');
  for (var index in input) {
      if( $( input[index] ).attr('data') == key ){
         return $( input[index] ).val();
      }
  }
}

function callupdate(table,index,WHERE){
  var lenght = 0;
  var item = dataRecord[ 0 ];
  for (var key in item) {lenght++}

  if(index!=undefined&&index!=""){
      var selectSQL = "UPDATE `tableR` SET `{KEY}`=\"{VALUE}\" {WHERE};";
      var selectkey = "";
      var index = 0;
      for (var key in item) {
          selectkey += "`" + key + "`=\"" + GetItemValue(key) + "\"";
          if(index!=lenght-1){
            selectkey += ","
          }
          index++;
      }
      selectSQL = selectSQL.replace(/`{KEY}`=\"{VALUE}\"/g, selectkey)
      selectSQL = selectSQL.replace(/{WHERE}/g, WHERE)
      selectSQL = selectSQL.replace(/tableR/g, table)
  }
  else {
      var selectSQL = "INSERT INTO `tableR` (`{KEY}`) VALUES ('{VALUE}');";
      var selectkey = "";
      var selectvalue = "";
      var index = 0;
      for (var key in item) {
          selectkey   += "`" + key + "`";
          selectvalue += "\"" + GetItemValue(key) + "\"";
          if(index!=lenght-1){
            selectkey   += ","
            selectvalue += ","
          }
          index++;
      }
      selectSQL = selectSQL.replace(/`{KEY}`/g, selectkey)
      selectSQL = selectSQL.replace(/'{VALUE}'/g, selectvalue)        
      selectSQL = selectSQL.replace(/tableR/g, table)
  }

  console.log( selectSQL );

  $.ajax({
    url: Helper.GetServerIP() + "/mgr/update",
              dataType: "text",
              type: "post",
              data: { address:Helper.addressCur, sessionToken:Helper.sessionToken , selectSQL:selectSQL },
              success: function (data) {
                alert(data);
                Table_Show()
                $('#ModalSetting').modal('hide')
              },
              error: function (err) {
                alert(err.responseText);
              }
  });
  
}

function liOnclick(e){
  ShowModalSetting( e.id.replace(/rtr-/g, "") );
}

function new_record(){
  ShowModalSetting("-1");
}

(function($) {
    console.log("init.js");
    
    addModalSetting()

    var pagenum = $(".paginate_button")
    for(var ii=0;ii<pagenum.length;ii++){
        $(pagenum[ii]).click(onPageitem)
    }

    $(pagenum[ii]).click(onPageitem)


    var dropdown_menu_key = $(".dropdown-filter .dropdown-menu-key")[0];
    if(dropdown_menu_key!=undefined){
      var innerHTML = '<a class="dropdown-item" style="text-align: left;" onclick="bodyNavClick(this)">{key}</a>';
      var table111 = $("#recordtable #thead_table111 .sorting");

      $(".dropdown-filter .dropdown-key").html( table111[0].innerText )

      for(var ii=0;ii<table111.length;ii++){
          var html = innerHTML.replace(/{key}/g, table111[ii].innerText  );
          var item_new = document.createElement("tbody");
          item_new.innerHTML = html;
          $(item_new).appendTo( $(dropdown_menu_key) );

      }
    }

})(jQuery);


